/*
-------------------------------------------------

	Font.cpp

	Dmitriy Kuzmenko (Dgut)

-------------------------------------------------
*/

#include "Font.h"
#include "File.h"
#include "Render.h"
#include "Texture.h"

namespace Autumn
{

const float Font::SIZE = 64.f;

Font::Font( const char * texture, const char * widths )
{
	Font::texture = gRender.GetTexture( texture );

	/*Font::texture->Bind();
	Font::texture->Parameter( GL_TEXTURE_MIN_FILTER, GL_LINEAR );
	Font::texture->Parameter( GL_TEXTURE_MAG_FILTER, GL_LINEAR );*/

	FILE * stream = gFile.Open( widths, "rb" );
	if( stream )
	{
		fread( Font::widths, sizeof( Font::widths ), 1, stream );
		fclose( stream );
	}
	else
		memset( Font::widths, 0, sizeof( Font::widths ) );
}

Font::~Font( void )
{
}

void Font::Print( HorizontalAlign ha, VerticalAlign va, float x, float y, float scale, const char * text ) const
{
	static float verts[ 8 ];
	static float tverts[ 8 ];

	const float LENGTH = StrLen( text, scale );
	const float CURRENT_SIZE = SIZE * scale;
	
	if( ha == CENTER )
		x -= LENGTH / 2.f;
	else if( ha == RIGHT )
		x -= LENGTH;
	
	if( va == MIDDLE )
		y -= CURRENT_SIZE / 2.f;
	else if( va == TOP )
		y -= CURRENT_SIZE;

	gRender.SetTexture( texture );

	while( *text )
	{
		const float COL = ( *text % 16 ) * 0.0625f;
		const float ROW = 1.0f - ( *text / 16 + 1 ) * 0.0625f;

		x += widths[ *text ] / 2.f * scale;

		tverts[ 0 ] = COL;
		tverts[ 1 ] = ROW;
		
		tverts[ 2 ] = COL + 0.0625f;
		tverts[ 3 ] = ROW;
		
		tverts[ 4 ] = COL + 0.0625f;
		tverts[ 5 ] = ROW + 0.0625f;
		
		tverts[ 6 ] = COL;
		tverts[ 7 ] = ROW + 0.0625f;
		
		verts[ 0 ] = x - SIZE / 2.f * scale;
		verts[ 1 ] = y;
		
		verts[ 2 ] = x + SIZE / 2.f * scale;
		verts[ 3 ] = y;
		
		verts[ 4 ] = x + SIZE / 2.f * scale;
		verts[ 5 ] = y + SIZE * scale;
		
		verts[ 6 ] = x - SIZE / 2.f * scale;
		verts[ 7 ] = y + SIZE * scale;
		
		gRender.DrawPolygon( verts, tverts, 4 );

		x += widths[ *text ] / 2.f * scale;

		text++;
	}
}

const float Font::StrLen( const char * text, float scale ) const
{
	float length = 0;

	while( *text )
		length += widths[ *text++ ];

	return length * scale;
}

}	// namespace Autumn